package com.siecom.transport.handler;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.siecom.bean.BankCardInfoBean;
import com.siecom.constconfig.ConstDefine;
import com.siecom.framework.bean.TradeLogBean;
import com.siecom.hostservice.MainActivity;
import com.siecom.module.DeviceCallback;
import com.siecom.module.DeviceInterface;
import com.siecom.module.EMVParam;
import com.siecom.module.EmvOptions;
import com.siecom.proto.Message;
import com.siecom.tool.ByteTool;
import com.siecom.tool.LogUtil;
import com.siecom.transport.CommServer;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

/**
 * Created by zhq on 2017/1/16.
 */

public class FinanHandler implements ServiceHandler {
    private static final String TAG = FinanHandler.class.getSimpleName();
    private CommServer server;

    @Override
    public void onReceive(CommServer server, Message.siecomproto msg,String message) {
        this.server = server;
        Log.e("FinanHandler", "FinanHandler onReceive");
        disposeMessage(msg);

    }

    public void disposeMessage(Message.siecomproto msg) {


        switch (msg.getCmd()) {
            case ConstDefine.IC_LOG_REQUEST:
            case ConstDefine.PIC_LOG_REQUEST:
            case ConstDefine.AUTO_LOG_REQUEST:
                readLog(msg);
                break;

            case ConstDefine.PIC_LOAD_REQUEST:
            case ConstDefine.IC_LOAD_REQUEST:
            case ConstDefine.AUTO_LOAD_REQUEST:
                readLoadLog(msg);
                break;

            case ConstDefine.ARQC_REQUEST:
                ARPCExecute(msg);
                break;
            case ConstDefine.CANCEL_FINAN_REQUEST:
                cancelTask(msg);
                break;

            default:
                readCardInfo(msg);
                break;
        }


    }


    public void readLoadLog(Message.siecomproto msg) {

        DeviceCallback callback = new DeviceCallback() {
            @Override
            public void onStart() {


            }

            @Override
            public void onError(Bundle bundle) {

                com.siecom.proto.Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                msgBuilder.setModule(ConstDefine.FINAN_MODULE);
                msgBuilder.setMsgid(msg.getMsgid());
                msgBuilder.setCmd(msg.getCmd() + 1);
                msgBuilder.setTimeout(msg.getTimeout());
                msgBuilder.setRespond(bundle.getString("message"));
                msgBuilder.setError(bundle.getInt("code"));
                com.siecom.proto.Message.siecomproto msg = msgBuilder.build();
                server.sendToRemote(msg);


            }

            @Override
            public void onSuccess(Bundle bundle) {
                List<TradeLogBean> list = bundle.getParcelableArrayList("data");
                Gson gson = new Gson();
                String respond = gson.toJson(list);
                com.siecom.proto.Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                msgBuilder.setModule(ConstDefine.FINAN_MODULE);
                msgBuilder.setMsgid(msg.getMsgid());
                msgBuilder.setCmd(msg.getCmd() + 1);
                msgBuilder.setTimeout(msg.getTimeout());
                msgBuilder.setRespond(respond);
                msgBuilder.setError(0);
                com.siecom.proto.Message.siecomproto msg = msgBuilder.build();
                server.sendToRemote(msg);

            }

            @Override
            public void onCompleted(Bundle bundle) {


            }
        };
        if (msg.getCmd() == ConstDefine.IC_LOAD_REQUEST) {
            DeviceInterface.readIcLoadLog(callback, null, msg.getTimeout(), false);
        } else if (msg.getCmd() == ConstDefine.PIC_LOAD_REQUEST) {
            DeviceInterface.readPicLoadLog(callback, null, msg.getTimeout(), false);
        } else if  (msg.getCmd() == ConstDefine.AUTO_LOAD_REQUEST) {
            DeviceInterface.readLoadLog(callback, null, msg.getTimeout(), false);
        }

    }

    public void cancelTask(Message.siecomproto msg){

        DeviceInterface.cancelFinancial();
        com.siecom.proto.Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
        msgBuilder.setModule(ConstDefine.FINAN_MODULE);
        msgBuilder.setMsgid(msg.getMsgid());
        msgBuilder.setCmd(msg.getCmd() + 1);
        msgBuilder.setRespond("Finan cancel");
        msgBuilder.setError(0);
        com.siecom.proto.Message.siecomproto respondMsg = msgBuilder.build();
        server.sendToRemote(respondMsg);

    }

    public void ARPCExecute(Message.siecomproto msg) {
        JSONObject json = null;
        int cardType = 0;
        String arpc = null;
        String script = null;
        try {
            json = new JSONObject(msg.getRequest());
            cardType = json.getInt("cardType");
            arpc = json.getString("arpc");
            script = json.getString("script");
        } catch (JSONException e) {
            e.printStackTrace();

        }
        DeviceInterface.ARPCExecuteScript(cardType, arpc, script, new DeviceCallback() {
            @Override
            public void onStart() {

            }

            @Override
            public void onError(Bundle bundle) {
                com.siecom.proto.Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                msgBuilder.setModule(ConstDefine.FINAN_MODULE);
                msgBuilder.setMsgid(msg.getMsgid());
                msgBuilder.setCmd(msg.getCmd() + 1);
                msgBuilder.setRespond(bundle.getString("message"));
                msgBuilder.setError(bundle.getInt("code"));
                com.siecom.proto.Message.siecomproto respondMsg = msgBuilder.build();
                server.sendToRemote(respondMsg);
            }

            @Override
            public void onSuccess(Bundle bundle) {
                JSONObject json = new JSONObject();
                try {
                    json.put("result", bundle.getInt("result"));
                    json.put("ScriptResult", bundle.getString("ScriptResult"));
                    json.put("TC", bundle.getString("TC"));
                }catch (JSONException e){

                }
                com.siecom.proto.Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                msgBuilder.setModule(ConstDefine.FINAN_MODULE);
                msgBuilder.setMsgid(msg.getMsgid());
                msgBuilder.setCmd(msg.getCmd() + 1);
                msgBuilder.setError(0);
                msgBuilder.setRespond(json.toString());
                com.siecom.proto.Message.siecomproto respondMsg = msgBuilder.build();
                server.sendToRemote(respondMsg);
            }

            @Override
            public void onCompleted(Bundle bundle) {


            }

        },msg.getTimeout(),false);
    }


    /**
     * 读交易日志
     * @param msg
     */
    public void readLog(Message.siecomproto msg) {

        DeviceCallback callback = new DeviceCallback() {
            @Override
            public void onStart() {


            }

            @Override
            public void onError(Bundle bundle) {

                com.siecom.proto.Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                msgBuilder.setModule(ConstDefine.FINAN_MODULE);
                msgBuilder.setMsgid(msg.getMsgid());
                msgBuilder.setCmd(msg.getCmd() + 1);
                msgBuilder.setTimeout(msg.getTimeout());
                msgBuilder.setRespond(bundle.getString("message"));
                msgBuilder.setError(bundle.getInt("code"));
                com.siecom.proto.Message.siecomproto msg = msgBuilder.build();
                server.sendToRemote(msg);


            }

            @Override
            public void onSuccess(Bundle bundle) {
                List<TradeLogBean> list = bundle.getParcelableArrayList("data");
                Log.e(TAG,"onSuccess list.size=" + list.size());
                Gson gson = new Gson();
                String respond = gson.toJson(list);
                 respond = parseTradeLog(list);
                com.siecom.proto.Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                msgBuilder.setModule(ConstDefine.FINAN_MODULE);
                msgBuilder.setMsgid(msg.getMsgid());
                msgBuilder.setCmd(msg.getCmd() + 1);
                msgBuilder.setTimeout(msg.getTimeout());
                msgBuilder.setRespond(respond);
                msgBuilder.setError(0);
                com.siecom.proto.Message.siecomproto msg = msgBuilder.build();
                server.sendToRemote(msg);

            }

            @Override
            public void onCompleted(Bundle bundle) {


            }
        };
        if (msg.getCmd() == ConstDefine.IC_LOG_REQUEST) {
            DeviceInterface.readIcLog(callback, null, msg.getTimeout(), false);
        } else if (msg.getCmd() == ConstDefine.PIC_LOG_REQUEST) {
            DeviceInterface.readPicLog(callback, null, msg.getTimeout(), false);
        }else if (msg.getCmd() == ConstDefine.AUTO_LOG_REQUEST) {
            DeviceInterface.autoReadLog(callback, null, msg.getTimeout(), false);
        }

    }
    @SuppressLint("DefaultLocale")
    public static String  parseTradeLog(List<TradeLogBean> list){
        LogUtil.e(TAG,"parseTradeLog list = " + list.size());
        StringBuffer buf = new StringBuffer();
        LogUtil.e(TAG,"parseTradeLog 111 ");
        buf.append(String.format("%02d",list.size()));
        LogUtil.e(TAG,"parseTradeLog 222 ");
        for (int i = 0; i < list.size(); i++) {
            LogUtil.e(TAG,"parseTradeLog 333 ");
            TradeLogBean bean = list.get(i);

            LogUtil.e(TAG,"parseTradeLog bean = " + bean.toString());
            StringBuffer bufInner = new StringBuffer();
            bufInner.append("P").append(getStrLength(bean.amount)).append(bean.amount); //授权金额
            bufInner.append("Q").append(getStrLength(bean.otherAmount)).append(bean.otherAmount); //其它金额
            bufInner.append("R").append(getStrLength(bean.TransCurrCode)).append(bean.TransCurrCode); //交易货币代码
            bufInner.append("S").append(getStrLength(bean.date)).append(bean.date); //交易日期
            bufInner.append("T").append(getStrLength(bean.TransType)).append(bean.TransType); //交易类型
            bufInner.append("U").append(getStrLength(bean.time)).append(bean.time); //交易时间
            bufInner.append("V").append(getStrLength(bean.CountryCode)).append(bean.CountryCode); //终端国家代码
            bufInner.append("W").append(getStrLength(bean.MerchName)).append(bean.MerchName); //商户名称
            bufInner.append("X").append(getStrLength(String.valueOf(bean.TransNo))).append(bean.TransNo); //应用交易计数器（ATC）
            buf.append(getStrLength(bufInner.toString())).append(bufInner);
        }
        LogUtil.e(TAG,"trade log == " + buf);
        return buf.toString();
    }
    private static String getStrLength(String str){
        return String.format("%03d", str.length());
    }
    public void readCardInfo(Message.siecomproto msg) {

        EmvOptions options = new EmvOptions();
        EMVParam emvParam = new EMVParam();
//        emvParam.parseFromBytes(msg.getExtion().toByteArray());
        options.setEmvParam(null);
        String[]  wantTags = null;
        try {
            JSONObject jsonObject = new JSONObject(msg.getRequest());
            if(jsonObject.has("wantTags")) {
                JSONArray jsonArray = jsonObject.getJSONArray("wantTags");
                wantTags = new String[jsonArray.length()];
                for (int i = 0; i < jsonArray.length(); i++) {
                    wantTags[i] = jsonArray.getString(i);
                }
            }
            if(jsonObject.has("time")){
                options.setTime(jsonObject.getString("time"));
            }
            if(jsonObject.has("TransNo")){
                options.setTransNo(jsonObject.getInt("TransNo"));
            }
            if(jsonObject.has("authorizedAmount")){
                options.setAuthorizedAmount(jsonObject.getInt("authorizedAmount"));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        DeviceCallback callback = new DeviceCallback() {
            @Override
            public void onStart() {

                switch (msg.getCmd()) {
                    case ConstDefine.IC_REQUEST:
                        // 11键盘  10指纹 9IC卡  8磁条卡  5蓝牙 6 身份证
                        MainActivity.getmSys().DLL_SysLedControl((byte) 9,(byte)1);
                        MainActivity.startInsideCard();
                        break;
                    case ConstDefine.PIC_REQUEST:
                        MainActivity.startNfcCard();
                        break;
                    case ConstDefine.MSR_REQUEST:
                        MainActivity.getmSys().DLL_SysLedControl((byte) 8,(byte)1);
//                        MainActivity.startSwipeCard();
                        break;
                    case ConstDefine.AUTO_REQUEST:
                        MainActivity.getmSys().DLL_SysLedControl((byte) 8,(byte)1);
                        MainActivity.getmSys().DLL_SysLedControl((byte) 9,(byte)1);
                        MainActivity.startInoneCard();
                        break;

                }
            }

            @Override
            public void onError(Bundle bundle) {

                com.siecom.proto.Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                msgBuilder.setModule(ConstDefine.FINAN_MODULE);
                msgBuilder.setMsgid(msg.getMsgid());
                msgBuilder.setCmd(msg.getCmd() + 1);
                msgBuilder.setTimeout(msg.getTimeout());
                msgBuilder.setRespond(bundle.getString("message"));
                msgBuilder.setError(bundle.getInt("code"));
                com.siecom.proto.Message.siecomproto msg = msgBuilder.build();
                server.sendToRemote(msg);

                MainActivity.playVoice(ConstDefine.OPERATE_FAIL);

                MainActivity.getmSys().DLL_SysLedControl((byte) 8,(byte)0);
                MainActivity.getmSys().DLL_SysLedControl((byte) 9,(byte)0);
            }

            @Override
            public void onSuccess(Bundle bundle) {
                BankCardInfoBean bean = bundle.getParcelable("data");
                Gson gson = new Gson();
                String respond = gson.toJson(bean);
                LogUtil.e(TAG,"BankCardInfoBean == " + bean.toString());
                if(msg.getCmd() == ConstDefine.MSR_REQUEST){
                    JSONObject jb = new JSONObject();
                    try {
                        jb.put("code",0);
                        jb.put("pan",bean.cardNo);
                        jb.put("track1",bean.oneMagneticTrack);
                        jb.put("track2",bean.twoMagneticTrack);
                        jb.put("track3",bean.threeMagneticTrack);
                        String track2 = bean.twoMagneticTrack;
                        if(!TextUtils.isEmpty(track2) && track2.length() > 12){
                            int index = track2.indexOf("=");
                            if(index < 0){
                                index = track2.indexOf("D");
                            }
                            String exp = track2.substring(index+1,index+5);
                            String serviceCode = track2.substring(index+5,index+8);
                            jb.put("serviceCode",serviceCode);
                            jb.put("expiredDate",exp);
                        }

                        respond = jb.toString();

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }else { //IC 和 NFC卡

                    int offset = bean.ICChipData.indexOf("9F26");
                    if(offset!=-1)
                        bean.ICChipData = bean.ICChipData.substring(offset, bean.ICChipData.length());

                    offset = bean.ICChipData.indexOf("9F34");
                    if(offset!=-1)
                        bean.ICChipData = bean.ICChipData.substring(0, offset);

                     JSONObject jb = new JSONObject();
                    try {
                        jb.put("code",0);
                        jb.put("pan",bean.cardNo);
                        jb.put("message55",bean.getICChipData());
                        jb.put("message35",bean.twoMagneticTrack);
                        jb.put("messagePan",bean.serialNo);
                        jb.put("tagList",bean.tagListInfo);

                        respond = jb.toString();

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                }

                com.siecom.proto.Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                msgBuilder.setMsgid(msg.getMsgid());
                msgBuilder.setModule(ConstDefine.FINAN_MODULE);
                msgBuilder.setCmd(msg.getCmd() + 1);
                msgBuilder.setTimeout(msg.getTimeout());
                msgBuilder.setRespond(respond);
                msgBuilder.setError(0);
                com.siecom.proto.Message.siecomproto msg = msgBuilder.build();
                server.sendToRemote(msg);

                MainActivity.playVoice(ConstDefine.OPERATE_SUCC);
                MainActivity.getmSys().DLL_SysLedControl((byte) 8,(byte)0);
                MainActivity.getmSys().DLL_SysLedControl((byte) 9,(byte)0);
            }

            @Override
            public void onCompleted(Bundle bundle) {
                switch (msg.getCmd()) {
                    case ConstDefine.IC_REQUEST:
                        MainActivity.stopInsideCard();
                        break;
                    case ConstDefine.PIC_REQUEST:
                        MainActivity.stopNfcCard();
                        break;
                    case ConstDefine.MSR_REQUEST:
                        MainActivity.stopSwipeCard();
                        break;
                    case ConstDefine.AUTO_REQUEST:
                        MainActivity.stopInoneCard();
                        break;

                }
                MainActivity.getmSys().DLL_SysLedControl((byte) 8,(byte)0);
                MainActivity.getmSys().DLL_SysLedControl((byte) 9,(byte)0);
            }
        };
        Log.e(TAG,  "msg.getCmd()===" + msg.getCmd());


        switch (msg.getCmd()) {
            case ConstDefine.IC_REQUEST:
                DeviceInterface.readIcInfo(callback, options,wantTags, msg, false);
                break;
            case ConstDefine.PIC_REQUEST:
                DeviceInterface.readPiccInfo(callback, options, wantTags,msg, false);
                break;
            case ConstDefine.MSR_REQUEST:
                DeviceInterface.readMsr(callback, options, msg, false);
                break;
            case ConstDefine.AUTO_REQUEST:
                DeviceInterface.autoCardInfo(callback, options,wantTags, msg, false);
                break;


        }

    }
}
